import Vue from 'vue'
import VueRouter from 'vue-router'
import Home from '../views/Home.vue'

import Login from '@/views/Login.vue'
import Register from '../views/Register'

import ProfileIndex from '../views/profile/Index'
import ProfileEdit from '../views/profile/Edit'
import ProfileFollow from '../views/profile/Follow.vue'
import ProfileStar from '../views/profile/Star.vue'
import ProfileComment from '../views/profile/Comment.vue'

import PostDetail from '../views/PostDetail.vue'
import MoreComment from '../views/MoreComment'

import Search from '../views/Search'
import Manage from '../views/Manage'

import Test from '../views/Test.vue'

Vue.use(VueRouter)

const routes = [
  {
    path: '/',
    name: 'Home',
    component: Home,
  },
  {
    path: '/login',
    component: Login,
  }, {
    path: '/register',
    component: Register
  },
  {
    path: '/profile',
    component: ProfileIndex,
    meta: {
      needAuth: true
    }
  },
  {
    path: '/edit',
    component: ProfileEdit,
    meta: {
      needAuth: true
    }
  },
  {
    path: '/follow',
    component: ProfileFollow,
    meta: {
      needAuth: true
    }
  },
  {
    path: '/star',
    component: ProfileStar,
    meta: {
      needAuth: true
    }
  },
  {
    path: '/comment',
    component: ProfileComment,
    meta: {
      needAuth: true
    }
  },
  {
    path: '/postdetail/:id',
    component: PostDetail
  },
  {
    path: '/morecomment/:id',
    component: MoreComment
  },
  {
    path: '/search',
    component: Search
  },
  {
    path: '/manage',
    component: Manage
  },
  {
    path: '/test',
    component: Test
  }
]

const router = new VueRouter({
  routes
})

// 添加全局路由守卫
// 拦截住所有跳转, 执行回调函数
router.beforeEach((to, from, next) => {
  console.log('看看当前路由元信息是什么');
  console.log(to.meta);
  // 如果我进入的地方是个人中心
  // 0. 最简单的写法, 直接 || 或逻辑进行判断
  // if(to.path == '/profile' || to.path == '/edit') {

  // 1. 将需要校验的页面配置成一个数组
  // const pagesNeedAuth = [
  //   '/profile',
  //   '/edit'
  // ]

  // // 如果我进入的地方是个人中心
  // if(pagesNeedAuth.indexOf(to.path) > -1) {
  // 2. 第三种判断方法, 可以给页面路由配置设置 meta, 在这里判断即可
  if(to.meta.needAuth) {
    // 判断 token 是否存在
    if(localStorage.getItem('token')) {
      // 存在则放行
      return next()
    } else {
      // 如果不存在,跳转到登录页
      return router.push('/login').catch(err => { })
    }
  }

  return next()
})

export default router
